package wc.Utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @ClassName:jdbcUtil
 * @Author: 鹿建文
 * @Date: 2022/4/2  - 16:58
 * @Describe:
 */
public class JdbcUtil {
    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        InputStream is = JdbcUtil.class.getResourceAsStream("/mysql.properties");
        try {
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private JdbcUtil() {

    }

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>() {
        @Override
        protected Connection initialValue() {
            Connection conn = null;
            try {
                conn = dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }
    };

    public static Connection getConnection() throws SQLException {
        Connection conn = threadLocal.get();
        if (conn != null) {
            return conn;
        }
        conn = dataSource.getConnection();
        threadLocal.set(conn);
        return conn;
    }

    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                        threadLocal.remove();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        System.out.println(getConnection());
        if (conn != null) {
            conn.close();
        }
        release(conn, null, null);
//
    }
}